<script setup lang='ts'>
import { ref, nextTick, computed } from "vue";
import { useAuthStore } from "@/stores/modules/auth";
import { useRouter } from "vue-router";

const router = useRouter();
const authStore = useAuthStore();
const menuList = computed(() => authStore.flatMenuListGet.filter((item: any) => !item.meta.isHide));

const searchMenuList = (queryString: string, cb: Function) => {
  const results = queryString ? menuList.value.filter(filterNodeMethod(queryString)) : menuList.value;
  console.log(results)
  cb(results);
};

const filterNodeMethod = (queryString: string) => {
  return (restaurant: any) => {
    return (
      restaurant.path.toLowerCase().indexOf(queryString.toLowerCase()) > -1 ||
      restaurant.meta.title.toLowerCase().indexOf(queryString.toLowerCase()) > -1
    );
  };
};

const handleClickMenu = (menuItem: Menu.MenuOptions | Record<string, any>) => {
  searchMenu.value = "";
  if (menuItem.meta.isLink) window.open(menuItem.meta.isLink, "_blank");
  else router.push(menuItem.path);
  closeSearch();
};

const isShowSearch = ref(false);
const menuInputRef = ref();
const searchMenu = ref("");

const handleOpen = () => {
  isShowSearch.value = true;
  nextTick(() => {
    setTimeout(() => {
      menuInputRef.value.focus();
    });
  });
};

const closeSearch = () => {
  isShowSearch.value = false;
};
</script>

<template>
  <div class="menu-search-dialog">
    <i :class="'iconfont icon-sousuo'" class="toolBar-icon" @click="handleOpen"></i>
    <el-dialog v-model="isShowSearch" fullscreen destroy-on-close :modal="false" :show-close="false" @click="closeSearch">
      <el-autocomplete
        ref="menuInputRef"
        placeholder="菜单搜索支持菜单名称、路径"
        v-model="searchMenu"
        :fetch-suggestions="searchMenuList"
        @select="handleClickMenu"
        @click.stop
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
        <template #default="{ item }">
          <el-icon>
            <component :is="item.meta.icon"></component>
          </el-icon>
          <span>{{ item.meta.title }}</span>
        </template>
      </el-autocomplete>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.menu-search-dialog {
  :deep(.el-dialog) {
    background-color: rgb(0 0 0 / 50%);
    border-radius: 0 !important;
    box-shadow: unset !important;
    .el-dialog__header {
      border-bottom: none !important;
    }
  }
  :deep(.el-autocomplete) {
    position: absolute;
    top: 100px;
    left: 50%;
    width: 550px;
    transform: translateX(-50%);
    .el-input__wrapper {
      background-color: var(--el-bg-color);
    }
  }
}
.el-autocomplete-suggestion__list {
    .el-icon {
      position: relative;
      top: 2px;
      font-size: 16px;
    }
    span {
      margin: 0 0 0 10px;
      font-size: 14px;
    }
  }
</style>
